﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using ServerLibrary.Abstract;
using ServerLibrary.Concrete;
using ServerLibrary.Infrastructure;
namespace ServerLibrary.Concrete
{


    /// <summary>
    /// Class which presents Task entity.
    /// </summary>
    public class Task : ITask
    {
        /// <summary>
        /// Contains http request
        /// </summary>
        private HttpListenerRequest request;

        /// <summary>
        /// Contains http response
        /// </summary>
        private HttpListenerResponse response;

        /// <summary>
        ///Contains file handler,which gets the file
        /// </summary>
        private IHandler fileHandler;

        public HttpListenerRequest Request { get; set; }

        public HttpListenerResponse Response { get; set; }

        public IHandler FileHandler { get; set; }

        public event TaskDoneHandler TaskDone;

        /// <summary>
        /// Deafult constructor
        /// </summary>
        public Task()
        {
            FileHandler = new FileHandler();
        }


        /// <summary>
        /// Constructs task with params
        /// </summary>
        /// <param name="request">Http request</param>
        /// <param name="response">Http response</param>
        /// <param name="fileHandler"> File Handler</param>
        public Task(HttpListenerRequest request, HttpListenerResponse response, IHandler fileHandler)
        {
            this.request = request;
            this.response = response;
            this.fileHandler = fileHandler;
        }

        public void Run(object threadContext)
        {
            byte[] file = null;
            string contentType;
            string replace = @"\";
            int resultCode = FileHandler.Handle(@"D:\Root" + Request.Url.AbsolutePath.Replace("/", replace), out file, out contentType);
            switch (resultCode)
            {
                case 200:
                    Response.ContentType = contentType;
                    Response.OutputStream.Write(file, 0, file.Length);
                    break;
                case 404:
                    Response.StatusCode=resultCode;
                    Response.StatusDescription = "File not found. 404";
                    file = Encoding.ASCII.GetBytes("<html><body><H1>File not found. 404</H1></body></html>");
                    Response.OutputStream.Write(file, 0, file.Length);
                    break;
            }
            Response.OutputStream.Close();
            OnTaskDone();
        }

        /// <summary>
        /// Raise the event
        /// </summary>
        public void OnTaskDone()
        {
            if (TaskDone != null)
            {
                TaskDone(this, null);
            }
        }

    }
}
